//
// Created by cmj on 2020/7/10.
//

#ifndef ERLUA_ERLUA_WRAP_H
#define ERLUA_ERLUA_WRAP_H

#include <functional>
#include "erlua_error.h"

static constexpr auto ERLUA_NIF_PID_META = "ErlNifPid";

class erlua_wrap {
public:
    lua_State *state;
    char *temp_buf;         // 读取字符的时候,临时存放字符串的buf,避免重复申请和释放
    void clean() const;
    void fetch_string_from_term(ErlNifEnv *env, ERL_NIF_TERM term) const;
    void load_file() const;
    void fetch_global_func() const;
    void push_param_from(ErlNifEnv *env, ERL_NIF_TERM term) const;
    void push_param_from_ls(ErlNifEnv *pEnvironment, ERL_NIF_TERM list) const;
    void pcall_func(int nargs, int nresults) const;
    ERL_NIF_TERM pop_params_to(ErlNifEnv *env);
    ERL_NIF_TERM get_term_from_index(ErlNifEnv *env, int idx=-1);
};

static erlua_wrap* erlua_get_state_from_env(ErlNifEnv *env, ErlNifResourceType* type, ERL_NIF_TERM term) {
    erlua_wrap *lw;
    if (!enif_get_resource(env, term, type, reinterpret_cast<void **>(&lw))) {
        throw erlua_exception("", erlua_global.not_lua_state);
    }
    return lw;
}

#endif //ERLUA_ERLUA_WRAP_H
